package meb

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/mosongcc/gosdk/weixin_oauth"
	"github.com/mosongcc/gotool/gcache"
	"github.com/mosongcc/gotool/gobjectid"
	"github.com/mosongcc/gotool/gtime"
	"gorm.io/gorm"
	"log/slog"
	"net/http"
	"time"
	"vitepress-serve/internal/common/hgin"
	"vitepress-serve/internal/model"
)

const PATH_WEIXIN_OAUTH2_CALLBACK = "/vpapi/meb/weixin-oauth-callback"

// WeixinOauthCallback 微信网页授权回调
func (ctl *Controller) WeixinOauthCallback(ctx *gin.Context) (err error) {
	var (
		host  = ctx.Request.Host
		code  = ctx.Query("code")
		state = ctx.Query("state")

		wechat = ctl.ConfigService.Wechat()
	)
	slog.Info("weixinOauthCallback", "code", code, "state", state)

	access, err := weixin_oauth.AccessToken(wechat.Appid, wechat.Secret, code)
	if err != nil {
		return
	}
	openid := access.Openid

	// 取用户信息
	var wxu weixin_oauth.UserInfoResult
	if access.Scope == weixin_oauth.SnsapiUserinfo {
		wxu, err = weixin_oauth.Userinfo(access.AccessToken, openid)
		if err != nil {
			return
		}
	}

	// 根据openid注册用户
	var user model.User
	var userOauth model.UserOauth
	if err = ctl.db.Where("openid = ?", openid).Take(&userOauth).Error; err != nil {
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			return
		}
		uid := gobjectid.Hex()
		err = ctl.db.Transaction(func(tx *gorm.DB) (err error) {
			userOauth.ID = gobjectid.Hex()
			userOauth.Uid = uid
			userOauth.Appid = wechat.Appid
			userOauth.Openid = openid
			userOauth.Ctime = gtime.NowF14()
			if err = tx.Create(&userOauth).Error; err != nil {
				return
			}
			user = model.User{
				Uid:       userOauth.Uid,
				Type:      model.USER_TYPE_USR,
				RegDomain: host,
				RegIp:     hgin.RemoteIP(ctx),
				Ctime:     gtime.NowF14(),
			}
			if err = tx.Create(user).Error; err != nil {
				return
			}
			return
		})
		if err != nil {
			return
		}
	}

	//更新微信渠道登录时间
	userOauth.LogTime = gtime.NowF14()
	userOauth.Mtime = userOauth.LogTime
	if err = ctl.db.Save(&userOauth).Error; err != nil {
		return
	}

	// 查询用户信息
	if err = ctl.db.Where("uid = ?", userOauth.Uid).Take(&user).Error; err != nil {
		return
	}
	// 更新用户信息
	user.LogTime = gtime.NowF14()
	user.LogIp = hgin.RemoteIP(ctx)
	user.Mtime = user.LogTime
	user.Avatar = wxu.Headimgurl
	user.Nickname = wxu.Nickname
	if user.Sex == "" {
		user.Sex = model.UserSex(fmt.Sprintf("%v", wxu.Sex))
	}
	if err = ctl.db.Where("uid = ?", user.Uid).Updates(&user).Error; err != nil {
		return
	}

	// 生成token写入缓存，key值为state
	token := hgin.GenToken(hgin.Token{Uid: userOauth.Uid, Type: string(user.Type)}, time.Now().Add(365*24*time.Hour))
	setJwtCookie(ctx, token)

	gcache.Set(ctl.cache, state, token, 10*time.Minute) // 给前端轮询查询

	//授权成功，跳转到网站首页
	ctx.Redirect(http.StatusFound, fmt.Sprintf("https://%s/", host))
	//ctx.Data(http.StatusOK, "text/html; charset=UTF-8", []byte("<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><div>授权成功</div>"))
	return
}
